package wfw.cn.ktc_friend.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import wfw.cn.ktc_common.entity.Result;
import wfw.cn.ktc_common.entity.ResultCode;
import wfw.cn.ktc_common.entity.StatusCode;
import wfw.cn.ktc_common.unit.IdWorker;
import wfw.cn.ktc_friend.client.UserClient;
import wfw.cn.ktc_friend.dao.FriendDao;
import wfw.cn.ktc_friend.entity.Friend;

/**
 * @Description tb_friend 服务层
 * @author admin
 * @date 2020-10-16 16:33:25
*/
@Service
public class FriendServiceImpl implements FriendService{

	@Autowired
	private FriendDao friendDao;

	@Autowired
	private IdWorker idWorker;

	@Autowired
	private UserClient userClient;

	/**
	* 查询全部列表
	* @return
	*/
	public List<Friend> findAll() {
		return friendDao.findAll();
	}

	/**
	* 条件查询+分页
	* @param whereMap
	* @param page
	* @param size
	* @return
	*/
	public Page<Friend> findSearch(Map whereMap, int page, int size) {
		Specification<Friend> specification = createSpecification(whereMap);
		PageRequest pageRequest =  PageRequest.of(page-1, size);
		return friendDao.findAll(specification, pageRequest);
	}

	/**
 	* 条件查询
	* @param whereMap
	* @return
	*/
	public List<Friend> findSearch(Map whereMap) {
		Specification<Friend> specification = createSpecification(whereMap);
		return friendDao.findAll(specification);
	}

	/**
	* 根据ID查询实体
	* @param id
	* @return
	*/
	public Friend findById(String id) {
		return friendDao.findById(id).get();
	}

	/**
	* 增加
	* @param friend
	*/
	public void add(Friend friend) {
		Result result = userClient.updateFollowCount(friend.getUserid(), 1);
		userClient.updateFansCount(friend.getFriendid(),1);
		if (result.getCode().equals(ResultCode.SUCCESS)){
			friendDao.save(friend);
		}
	}

	/**
	* 修改
	* @param friend
	*/
	public void update(Friend friend) {
		friendDao.save(friend);
	}

	/**
	* 删除
	* @param id
	*/
	public void deleteById(String id) {
		Friend friend = friendDao.findByUserid(id);
		friendDao.deleteByUserid(id);
		userClient.updateFollowCount(id,-1);
		userClient.updateFansCount(friend.getFriendid(),-1);
	}

	/**
	* 动态条件构建
	* @param searchMap
	* @return
	*/
	private Specification<Friend> createSpecification(Map searchMap) {

		return new Specification<Friend>() {

			@Override
			public Predicate toPredicate(Root<Friend> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicateList = new ArrayList<Predicate>();

				return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));
			}
		};
	}

}
